package client;

import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;

import stalker.Stalker;
import client.gui.roombox.RoomBox;
import client.network.ServiceRequestCenter;
import client.session.SessionType;
import client.session.SessionVisitor;
import data.Data;

public class Chat implements SessionType {
  
  private final List<RoomBox> boxes_;
  private final ServiceRequestCenter servicer_;
  private final JPanel display_;
  
  public Chat(ServiceRequestCenter servicer) {
    assert (servicer != null);
    
    // TODO Display
    display_ = new JPanel();
    
    servicer_ = servicer;
    boxes_ = new ArrayList<RoomBox>();
  }
  
  public JPanel getDisplay() {
    return display_;
  }
  
  public synchronized void spawnBox(Stalker room) {
    assert room != null;
    boolean found = false;
    for (RoomBox box : boxes_) {
      if (box.getRoom().equals(room)) {
        box.setVisible(true);
        found = true;
      }
    }
    if (!found) {
      System.out.println("creating new box...");
      RoomBox new_box = new RoomBox(room, servicer_);
      System.out.println("making it visible!");
      new_box.setVisible(true);
      boxes_.add(new_box);
    }
  }
  
  public void receiveData(Stalker sender, Data data) {
    assert sender != null && data != null;
    for (RoomBox box : boxes_) {
      box.receiveData(sender, data);
    }
  }
  
  public void receiveInvitation(Stalker inviter, Stalker location) {
    assert inviter != null && location != null;
    spawnBox(location);
  }

  public <T> T accept(SessionVisitor<T> visitor) {
    return visitor.visit(this);
  }

  public void cleanUp() {
    for (RoomBox box : boxes_) {
      if (box.isVisible()) {
        box.setVisible(false);
      }
    }
  }
  
}
